<script setup>
import { onMounted, ref, watch } from 'vue'
import { queryPageApi, deleteApi, addApi, queryInfoApi, updateApi } from '@/api/clazz'
import { queryAllApi as queryAllEmpsApi } from '@/api/emp'
import { ElMessage, ElMessageBox } from 'element-plus';

//新增/编辑班级对话框元数据
const dialogVisible = ref(false)
const dialogTitle = ref('')
const clazz = ref({
  "name": "",
  "room": "",
  "beginDate": "",
  "endDate": "",
  "masterId": "",
  "subject": ""
})
// 获取表单引用
const formRef = ref()

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '班级名称不能为空', trigger: 'blur' }
  ],
  beginDate: [
    { required: true, message: '开课时间不能为空', trigger: 'blur' }
  ],
  endDate: [
    { required: true, message: '结课时间不能为空', trigger: 'blur' }
  ],
  subject: [
    { required: true, message: '学科不能为空', trigger: 'change' }
  ]
}

//班主任列表
const masters = ref([])
//学科列表
const subjects = ref([
  {name: "java", value: 1}, 
  {name: "前端", value: 2}, 
  {name: "大数据", value: 3}, 
  {name: "Python", value: 4}, 
  {name: "Go", value: 5}, 
  {name: "嵌入式", value: 6}
])

//新增班级
const addClazz = async () => { 
  clazz.value = {
    "name": "",
    "room": "",
    "beginDate": "",
    "endDate": "",
    "masterId": "",
    "subject": ""
  }
  dialogTitle.value = '新增班级';
  dialogVisible.value = true;
  clearValidate();
}

//修改班级
const edit = async (id) => { 
  dialogTitle.value = '修改班级';
  dialogVisible.value = true;
  const result = await queryInfoApi(id);
  if (result.code) { 
    clazz.value = result.data;
  }
}


//搜索表单数据
const searchForm = ref({
  name: '',
  begin: '',
  end: '',
  date: []
});
//侦听搜索表单起始日期
watch(() => searchForm.value.date , (newVal, oldVal) => { 
  searchForm.value.begin = newVal[0];
  searchForm.value.end = newVal[1];
});

//表格内容
const clazzList = ref([]);

//分页参数
const total = ref(100);
const page = ref(1);
const pageSize = ref(10);
const background = ref(true);

//页码变化时触发
const handleCurrentChange = (val) => {
  page.value = val;
  search();
}
//每页记录数变化时触发
const handleSizeChange = (val) => {
  pageSize.value = val;
  search();
}

//钩子函数
onMounted(async () => { 
  const result = await queryAllEmpsApi();
  if (result.code) { 
    masters.value = result.data;
  }
  search();
});

//查询
const search = async () => { 
  const result = await queryPageApi(
    searchForm.value.name, 
    searchForm.value.begin, 
    searchForm.value.end, 
    page.value, 
    pageSize.value
  );

  if (result.code) { 
    clazzList.value = result.data.rows;
    total.value = result.data.total;
  }
}

//清空查询条件
const clear = () => { 
  searchForm.value = {
    name: '',
    begin: '',
    end: '',
    date: []
  }
  search();
}

//删除班级
const del = async (id) => { 
    ElMessageBox.confirm('请确认是否删除所选员工, 删除操作不可撤销!','警告',
    {
      confirmButtonText: '确认删除', cancelButtonText: '取消', 
      type: 'warning',
      confirmButtonClass: 'el-button--danger', //确认按钮样式为 danger
      autofocus: false  //取消自动聚焦于确认按钮
    }
  ).then(async () => { //确认
    const result = await deleteApi(id);
    if (result.code) { 
      ElMessage.success('删除班级成功');
      search();
    } else {
      ElMessage.error(result.msg);
    }
  }).catch(() => {
    ElMessage.info('取消删除员工');
  })
}

// 保存班级信息
const saveClazz = async () => {
  //表单验证
  if (!formRef.value) { 
    return;
  }
  formRef.value.validate(async (valid) => {
    let result;
    if (valid) { // 验证通过，执行保存操作
      if (!clazz.value.id) { // 添加
        result = await addApi(clazz.value);
      } else { // 修改
        result = await updateApi(clazz.value);
      }
      if (result.code) {  // 保存成功
        ElMessage.success('保存成功');
        dialogVisible.value = false;
        search();
      } else { // 保存失败
        ElMessage.error(result.msg);
      }
    } else { // 验证失败
      ElMessage.error('请填写必填项')
    }
  })
}

//清空表单验证作用域
const clearValidate = () => { 
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}
</script>

<template>
  <h1>班级管理</h1>
  <!-- 搜索表单 -->
  <div class="container">
    <el-form :inline="true" :model="searchForm" class="demo-form-inline">
      <el-form-item label="班级名称">
        <el-input v-model="searchForm.name" placeholder="请输入班级名称" clearable />
      </el-form-item>
      <el-form-item label="结课时间"> 
        <el-date-picker
          v-model="searchForm.date"
          type="daterange"
          value-format="YYYY-MM-DD"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="info" @click="clear()">清空</el-button>
      </el-form-item>
    </el-form>
  </div>

  <!-- 功能按钮 -->
  <div class="container"> 
    <el-button type="success" @click="addClazz()">+ 新增班级</el-button>
  </div>

  <!-- 表格内容 -->
  <div class="container">
    <el-table :data="clazzList" border style="width: fit-content">
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column prop="name" label="班级名称" width="180" align="center" />
      <el-table-column prop="room" label="班级教室" width="100" align="center" />
      <el-table-column prop="masterName" label="班主任" width="120" align="center" />
      <el-table-column prop="beginDate" label="开课时间" width="150" align="center" />
      <el-table-column prop="endDate" label="结课时间" width="150" align="center" />
      <el-table-column prop="status" label="状态" width="120" align="center" />
      <el-table-column prop="updateTime" label="最后操作时间" width="180" align="center" />
      <el-table-column label="操作" width="200" align="center" >
        <template #default="scope">
            <el-button size="small" type="primary" @click="edit(scope.row.id)"><el-icon><Edit /></el-icon>编辑</el-button>
            <el-button size="small" type="danger" @click="del(scope.row.id)"><el-icon><Delete /></el-icon>删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!-- 分页条 -->
  <div class="container">
    <el-pagination
      v-model:current-page="page"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 20, 30, 50, 100]"
      :background="background"
      :size="size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>

  <!-- 新增/编辑 班级Dialog对话框 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="800">
    <el-form 
      ref="formRef"
      :model="clazz"
      :rules="formRules"
      style="max-width: 700"
      label-width="auto"
    >
      <el-form-item label="班级名称" prop="name" required>
        <el-input v-model="clazz.name" />
      </el-form-item>
      <el-form-item label="班级教室">
        <el-input v-model="clazz.room" />
      </el-form-item>
      <el-form-item label="开课时间" prop="beginDate" required>
        <el-date-picker
          v-model="clazz.beginDate"
          type="date"
          placeholder="请选择开课时间"
          style="width: 100%"
          format="YYYY-MM-DD" 
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="结课时间" prop="endDate" required>
        <el-date-picker
          v-model="clazz.endDate"
          type="date"
          placeholder="请选择结课时间"
          style="width: 100%"
          format="YYYY-MM-DD" 
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="班主任">
        <el-select v-model="clazz.masterId" placeholder="请选择班主任">
          <el-option v-for="m in masters" :key="m.value" :label="m.name" :value="m.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="学科" prop="subject" required>
        <el-select v-model="clazz.subject" placeholder="请选择学科" >
          <el-option v-for="s in subjects" :key="s.value" :label="s.name" :value="s.value" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveClazz">保存</el-button>
      </div>
    </template>
  </el-dialog>
  
</template>

<style scoped>
.container {
  margin: 10px 0;
}

</style>